package com.lzs.bootsafety.common.config.druid;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URL;
@WebFilter(filterName = "Moni",urlPatterns = "/moni/druid/login")
public class DruidLoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = ((HttpServletResponse) servletResponse);
        String requestUrl = request.getRequestURL().toString();
        // 针对druid做自动登录
        if(requestUrl.contains("/moni/druid/login")){
            String queryString = "loginUsername=admin&loginPassword=admin";
            // 获取完整路径
            StringBuffer url = new StringBuffer(requestUrl);
            // 获取路径加上项目名称
            String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append(request.getServletContext().getContextPath()).append("/").toString();
            URL newUrl = new URL(tempContextUrl + "druid/submitLogin?" + queryString);
            response.setStatus(307);
            response.getStatus();
            response.setHeader("Location", newUrl.toString());
            response.setHeader("Connection", "close");
            //允许所有跨域请求
            response.addHeader("Access-Control-Allow-Origin", "*");
        }else {
            filterChain.doFilter(request,response);
        }
    }
}
